﻿#include <iostream>

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"

#include "camera.h"

using namespace std;
using namespace cv;

VideoCapture capture;
Mat frame;

bool openCamera(int index, double width, double height, double fps) {
    try {
        capture.release();
        capture.open(index, cv::CAP_DSHOW);
        if (!capture.isOpened()) throw string("Camera is not opened!");
        capture.set(cv::CAP_PROP_FRAME_WIDTH, width);
        capture.set(cv::CAP_PROP_FRAME_HEIGHT, height);
        capture.set(cv::CAP_PROP_FPS, fps);
        double w = capture.get(cv::CAP_PROP_FRAME_WIDTH);
        double h = capture.get(cv::CAP_PROP_FRAME_HEIGHT);
        double f = capture.get(cv::CAP_PROP_FPS);
        printf("Camera ON: %dx%d, %.2f FPS \n\n", (int)w, (int)h, f);
    }
    catch (...) {
        return false;
    }
    return true;
}

bool openVideo(char* path) {
    try {
        capture.release();
        capture.open(path);
        if (!capture.isOpened()) throw string("Video is not opened!");
        int count = (int)capture.get(cv::CAP_PROP_FRAME_COUNT);
        double w = capture.get(cv::CAP_PROP_FRAME_WIDTH);
        double h = capture.get(cv::CAP_PROP_FRAME_HEIGHT);
        double f = capture.get(cv::CAP_PROP_FPS);
        printf("Video INFO: about %d frames, %dx%d, %.2f FPS \n", count, (int)w, (int)h, f);
    }
    catch (...) {
        return false;
    }
    return true;
}

bool readFrame(unsigned int sleepTime) {
    cv::waitKey(sleepTime);
    return capture.read(frame);
}

void close() {
    frame.release();
    capture.release();
}
